﻿using Kairos.Models;
using Kairos.Properties;
using PagedList;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;

namespace Kairos.Controllers
{
    public enum Reason
    {
        Standard,
        Affect,
        Force,

        /// <summary>
        /// SqlException.Number 547
        /// </summary>
        Delete
    }

    public class VtomController : Controller
    {
        private myContext db = new myContext();

        //
        // GET: /Vtom/

        [AccessControl(Roles.All)]
        public ActionResult Index(int? page)
        {
            string filter = null;

            if (Request.Cookies.AllKeys.Contains(Utilities.CookieNameVtomJobsFilter))
                filter = Request.Cookies[Utilities.CookieNameVtomJobsFilter].Value;

            if (filter != null)
                ViewBag.Filter = filter;

            var vtoms = db.Vtoms.Where(v => v.DocID != null);

            //     Compare strings using ordinal sort rules and ignoring the case of the strings
            //     being compared.

            if (filter != null)
                vtoms.Where(v => v.Titre.ToLower().StartsWith(filter.ToLower()));

            // Nugget for easily paging through any IEnumerable/IQueryable in Asp.Net MVC
            // http://github.com/TroyGoode/PagedList

            int pageNumber = (page ?? 1);

            return View(vtoms.OrderBy(o => o.Titre).ToPagedList(pageNumber, Settings.Default.PageSize));
        }

        //
        // GET: /Vtom/Alarme

        [AccessControl(Roles.All)]
        public ActionResult Alarme(int? page)
        {
            var vtoms = db.Vtoms.Where(d => d.DocID == null);

            // Nugget for easily paging through any IEnumerable/IQueryable in Asp.Net MVC
            // http://github.com/TroyGoode/PagedList

            int pageNumber = (page ?? 1);

            return View(vtoms.OrderBy(o => o.Titre).ToPagedList(pageNumber, Settings.Default.PageSize));
        }

        //
        // GET: /Vtom/Redirect/

        [AccessControl(Roles.All)]
        public ActionResult Redirect(string env, string app, string job)
        {
            var items = new List<string>();

            items.Add(env);
            items.Add(app);
            items.Add(job);

            string titre = string.Join("/", items);

            // LINQ to Entities with French_CS_AS column collation
            Vtom vtom = db.Vtoms.SingleOrDefault(i => i.Titre == titre);

            if (vtom == null)
            {
                return HttpNotFound();
            }

            if (vtom.DocID == null)
            {
                return RedirectToAction("Edit", new { id = vtom.ID, reason = Reason.Force });
            }

            return Redirect(Url.Action("Details", "Doc", new { id = vtom.DocID }) + (string.IsNullOrWhiteSpace(vtom.Variables) ? string.Empty : "?" + vtom.Variables));
        }

        //
        // GET: /Vtom/Edit/5

        [AccessControl(Roles.All)]
        public ActionResult Edit(Reason reason, int id = 0)
        {
            Vtom vtom = db.Vtoms.Find(id);
            if (vtom == null)
            {
                return HttpNotFound();
            }

            ViewBag.Reason = reason;

            return View(vtom);
        }

        //
        // POST: /Vtom/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AccessControl(Roles.Administrator | Roles.Worker)]
        public ActionResult Edit(Vtom vtom, Reason reason, string filter)
        {
            Document document = db.Documents.Find(vtom.DocID);

            if (document == null)
                ModelState.AddModelError("DocId", "Le Document spécifié n'existe pas.");
            else if (document.MetaData_1.Nom != Settings.Default.VtomConsigne)
                ModelState.AddModelError("DocId", "Le Document spécifié n'est pas de type " + Settings.Default.VtomConsigne + ".");

            if (ModelState.IsValid)
            {
                db.Entry(vtom).State = EntityState.Modified;
                db.SaveChanges();

                if (reason == Reason.Force)
                    return Redirect(Url.Action("Details", "Doc", new { id = vtom.DocID }) + (string.IsNullOrWhiteSpace(vtom.Variables) ? string.Empty : "?" + vtom.Variables));
                else if (reason == Reason.Affect)
                    return RedirectToAction("Alarme");
                else if (reason == Reason.Standard)
                    return RedirectToAction("Index", new { filter = filter });
            }

            ViewBag.Reason = reason;

            return View(vtom);
        }
    }
}
